package com.guaoran.source.zookeeper.common;

import com.guaoran.source.zookeeper.config.ZookeeperConfig;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/14 12:50
 */
public class ServiceRegisterCenterImpl implements ServiceRegisterCenter {
    private CuratorFramework curatorFramework = ZookeeperConfig.initCuratorFramework();
    @Override
    public void registerCenter(String serviceName,String serviceAddress) {
        try {
            serviceName = "/" + serviceName;
            //判断服务节点是否存在，不存在则创建新的持久化节点
            if(curatorFramework.checkExists().forPath(serviceName) == null){
                curatorFramework.
                        create().
                        creatingParentsIfNeeded().
                        withMode(CreateMode.PERSISTENT).
                        forPath(serviceName,"0".getBytes());
            }
            //创建服务地址的临时节点
            String tempNode =
                    curatorFramework.
                    create().
                    withMode(CreateMode.EPHEMERAL).
                    forPath(serviceName+"/"+serviceAddress,"0".getBytes());
            System.out.println("服务地址创建成功"+tempNode);
        } catch (Exception e) {
            throw new RuntimeException("服务地址节点创建失败"+e);
        }
    }
}
